﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExitGames.Logging;
using Photon.SocketServer;
using ServerFramework.Implementation.Client;
using ServerFramework.Implementation.Handler;
using ServerFramework.Implementation.Server;
using ServerFramework.Interfaces.Application;
using ServerFramework.Interfaces.Client;
using ServerFramework.Interfaces.Server;
using ServerFramework.Interfaces.Telegram;
using TypeDefs;

namespace MasterServer.Handler.Request
{
    public class RealmListRequestHandler : ClientTelegramHandler
    {
        private IServerPeerRegistry<IServerPeer> ServerPeerRegistry { get; }
        
        public RealmListRequestHandler(ILogger logger, IServerPeerRegistry<IServerPeer> serverPeerRegistry) : base(logger)
        {
            ServerPeerRegistry = serverPeerRegistry;
        }

        public override TelegramHandlerTypes HandlerType => TelegramHandlerTypes.Request;
        public override byte Code => (byte) OperationCodes.Transfer;
        public override int? SubCode => (int?) OperationSubCodes.RequestRealmList;

        public override bool HandleTelegram(ITelegram telegram, IClientPeer clientPeer)
        {
            Logger.InfoFormat("Trying to handle telegram of type={0}, code={1}, sub-code={2}", telegram.Type,
                telegram.Code, telegram.SubCode);

            var peer = clientPeer as ClientPeer;

            var realms = ServerPeerRegistry.GetServerPeers().Single(c => c.Key == ServerTypes.RealmServer);

            Logger.InfoFormat("{0} - {1}", realms.Key, realms.Value.PeerId);
            
            if (realms.Value != null)
            {
                telegram.Parameters.Add((byte)ParameterCodes.RealmName, realms.Value.Server.ServerName);

                peer?.SendOperationResponse(new OperationResponse(telegram.Code, telegram.Parameters), new SendParameters());

                return true;
            }

            Logger.ErrorFormat("No realms found!");
            
            return true;
            
        }
    }
}
